//
//  CallReminderViewController.m
//  EquesCat
//
//  Created by Chun Hung Cheung on 2025/4/1.
//

#import "CallReminderViewController.h"
#import "VL5CallVideoVController.h"
#import "VL4CallVideoVController.h"
@interface CallReminderViewController ()
@property(nonatomic,strong)UIImageView *lockImageview;
@property(nonatomic,strong)dispatch_source_t can_open_vl0_time;
@property(nonatomic,strong)UIImageView *incomingImageView;

@end

@implementation CallReminderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setup];
    
    self.incomingImageView.backgroundColor = [UIColor clearColor];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:FILETRANS object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatepicture:) name:FILETRANS object:nil];
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:DEVST object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismiss:) name:DEVST object:nil];
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:OPEN_SMART_LOCK_RESULT object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(open_smart_lock_result:) name:OPEN_SMART_LOCK_RESULT object:nil];
    
    
}

- (void)dismiss:(NSNotification*)nitifacation
{
    NSDictionary *dict =  [nitifacation object];
    
    /*
     {
         bid = 32a593190aee6d3c2045360049e2883f;
         method = devst;
         name = "E0D31A7141E8-32a59319";
         nick = VL4;
         remoteupg = 0;
         role = 1016;
         stat = 1;
         status = 1;
         type = 1016;
         uid = 32a593190aee6d3c2045360049e2883f;
     }
     */
    
    if ([self.bid isEqualToString:[dict objectForKey:@"bid"]]) {
        [self dismissViewControllerAnimated:YES completion:^{
        }];
    }

}

- (UIImageView*)incomingImageView
{
    if (!_incomingImageView) {
        _incomingImageView = [[UIImageView alloc]init];
       [self.view addSubview:_incomingImageView];
       [_incomingImageView mas_makeConstraints:^(MASConstraintMaker *make) {
           make.top.equalTo(self.view.mas_top).offset([UIDevice dev_statusBarHeight]);
           make.centerX.equalTo(self.view.mas_centerX);
           make.width.mas_equalTo(160);
           make.height.mas_equalTo(160);
       }];
    }
    return _incomingImageView;
}


- (void)setup
{
    if ([[_msgJson objectForKey:@"type"] intValue] == 1  ||  [[_msgJson objectForKey:@"op_type"] intValue] == 1) {
        self.op_type = 1;
    }else{
        self.op_type = 0;
    }
    self.view.backgroundColor  = [UIColor blackColor];
    UIImageView *bjImageView = [[UIImageView alloc]init];
    // 来电背景图片
     bjImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"image_bg_incoming_calls_new.png"]];
    [self.view addSubview:bjImageView];
    [bjImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
    }];
    CGFloat height = 90;
    {
        height = 60;
        //创建三个按钮  语言 视频 挂断
        NSArray *imageArray2 = @[@"vl0_video_show",@"remote_vl0_lock",@"vl0_hang_up"];
        
        CGFloat width = [UIScreen mainScreen].bounds.size.width / imageArray2.count;
        for (int i = 0;  i < imageArray2.count; i++) {
           
               UIButton *button = [[UIButton alloc] init];
              [button setImage:[UIImage imageNamed:imageArray2[i]] forState:UIControlStateNormal];
                  [self.view addSubview:button];
              [button mas_makeConstraints:^(MASConstraintMaker *make) {
                   make.bottom.equalTo(self.view.mas_bottom).offset(-110);
                   make.width.mas_equalTo(width);
                   make.height.mas_equalTo(height);
                   make.left.mas_equalTo(self.view.mas_left).offset(width*i);
               }];
               button.tag = 1111 + i;
              [button addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
              [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            
            if (i == 1) {
                
                 self.lockImageview = [[UIImageView alloc]init];
                [self.view addSubview:self.lockImageview];
                [self.lockImageview mas_makeConstraints:^(MASConstraintMaker *make) {
                     make.top.equalTo(button.mas_bottom).offset(10);
                     make.width.mas_equalTo(16);
                     make.height.mas_equalTo(17);
                     make.centerX.mas_equalTo(button.mas_centerX).offset(-20);
                 }];
                self.lockImageview.animationImages =   [NSArray arrayWithObjects:
                                                      [UIImage imageNamed:@"vl0_count1@3x.png"],
                                                      [UIImage imageNamed:@"vl0_count2@3x.png"],
                                                      [UIImage imageNamed:@"vl0_count3@3x.png"],
                                                      [UIImage imageNamed:@"vl0_count4@3x.png"],[UIImage imageNamed:@"vl0_count5@3x.png"],nil];
                 self.lockImageview.animationDuration = 0.5;
                 self.lockImageview.animationRepeatCount = 0;
                 self.lockImageview.tag = 1315;
                [self.lockImageview startAnimating];
                [self.view bringSubviewToFront:_lockImageview];
                
                UIButton *lock_button = [UIButton buttonWithType:UIButtonTypeCustom];
               [self.view addSubview:lock_button];
               [lock_button mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(self.lockImageview.mas_right);
                    make.width.mas_equalTo(40);
                    make.height.mas_equalTo(20);
                    make.centerY.mas_equalTo(self.lockImageview.mas_centerY);
                }];
                lock_button.tag = 1314;
               [lock_button setTitleColor:[HexChangeRGB colorWithHexString:@"#FFECC0"] forState:UIControlStateNormal];
                lock_button.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
               [self.view bringSubviewToFront:lock_button];
                
                __block int timeout = self.vl0time; // 倒计时时间
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                _can_open_vl0_time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                dispatch_source_set_timer(_can_open_vl0_time,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                dispatch_source_set_event_handler(_can_open_vl0_time, ^{
                     timeout--;
                    
                     dispatch_async(dispatch_get_main_queue(), ^{
                        
                         UIButton *sender = [self.view viewWithTag:1314];
                         [sender setTitle:[NSString stringWithFormat:@"00:%02d",timeout] forState:UIControlStateNormal];
                         [sender SG_imagePositionStyle:SGImagePositionStyleDefault spacing:4];
                     });
                    if (timeout <= 0) {
                        if(_can_open_vl0_time){
                           
                            dispatch_async(dispatch_get_main_queue(), ^{
                                
                                 UIButton *sender = [self.view viewWithTag:1314];
                                [sender removeFromSuperview];
                                 sender = nil;
                                
                               
                                 if (_lockImageview) {
                                    [_lockImageview removeFromSuperview];
                                     _lockImageview = nil;
                                }
                                
                                UIButton *sender1 = [self.view viewWithTag:1112];
                                [sender1 setImage:[UIImage imageNamed:@"vlo_open_lock_unavailable"] forState:UIControlStateNormal];
                                 sender1.userInteractionEnabled = NO;
                            });
                            
                           dispatch_source_cancel(_can_open_vl0_time);
                            _can_open_vl0_time = nil;
        
                        }
                    }
                });
                dispatch_resume(_can_open_vl0_time);
                
             }
            
          }
    }
}



- (void)BtnClick:(UIButton*)sender
{

    switch (sender.tag) {
        case 1113:
        { //挂断
           
             NSLog(@"挂断");
          
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }
            break;
        
        case 1111:
          { //视频
    
            if(_can_open_vl0_time){
               dispatch_source_cancel(_can_open_vl0_time);
               _can_open_vl0_time = nil;
            }
            

            FBDevicesList *devices =  [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@ ",bg_sqlKey(@"bid"),bg_sqlValue(self.bid),bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken])]] firstObject];
        

              if (devices.role == EQUESVL5 || devices.role == EQUESVL5NT ) {
                  
                  
                  VL5CallVideoVController *callController = [[VL5CallVideoVController alloc]init];
                  callController.bid = self.bid;
                  NSString *strMethod = [_msgJson objectForKey:@"method"];
                  if ([strMethod isEqualToString:@"call_v2"]) {
                      callController.bid = [_msgJson objectForKey:@"from"];
                      if ([_msgJson objectForKey:@"peerid"]) {
                          callController.peer_id = [_msgJson objectForKey:@"peerid"];
                      }
                      
                      if ([_msgJson objectForKey:@"rtcserverip"]) {
                      
                          NSString *callMessag = [[NSUserDefaults standardUserDefaults] objectForKey:@"rtcudpip"];
                          int port =  [[[NSUserDefaults standardUserDefaults] objectForKey:@"rtcudpport"] intValue];
                          
                            if([[_msgJson objectForKey:@"netType"] intValue] == 1 && callMessag.length > 1 && port > 0 && devices.netType == 1){
                                callController.rtcip   = [_msgJson objectForKey:@"rtcudpip"];
                                callController.rtcport = [[_msgJson objectForKey:@"rtcudpport"] intValue];
                                callController.netType = [[_msgJson objectForKey:@"netType"] intValue];
                            }else{
                                callController.rtcip   = [_msgJson objectForKey:@"rtcserverip"];
                                callController.rtcport = [[_msgJson objectForKey:@"rtcserverport"] intValue];
                            }
                      }
                  }
          
                   callController.modalPresentationStyle =  UIModalPresentationFullScreen;
                  [self presentViewController:callController animated:YES completion:^{
                  }];
                  
                  
                  
              }else{
                  
                  VL4CallVideoVController *callController = [[VL4CallVideoVController alloc]init];
                  callController.bid = self.bid;
                  NSString *strMethod = [_msgJson objectForKey:@"method"];
                  if ([strMethod isEqualToString:@"call_v2"]) {
                      callController.bid = [_msgJson objectForKey:@"from"];
                      if ([_msgJson objectForKey:@"peerid"]) {
                          callController.peer_id = [_msgJson objectForKey:@"peerid"];
                      }
                      
                      if ([_msgJson objectForKey:@"rtcserverip"]) {
                      
                          NSString *callMessag = [[NSUserDefaults standardUserDefaults] objectForKey:@"rtcudpip"];
                          int port =  [[[NSUserDefaults standardUserDefaults] objectForKey:@"rtcudpport"] intValue];
                          
                            if([[_msgJson objectForKey:@"netType"] intValue] == 1 && callMessag.length > 1 && port > 0 && devices.netType == 1){
                                callController.rtcip   = [_msgJson objectForKey:@"rtcudpip"];
                                callController.rtcport = [[_msgJson objectForKey:@"rtcudpport"] intValue];
                                callController.netType = [[_msgJson objectForKey:@"netType"] intValue];
                            }else{
                                callController.rtcip   = [_msgJson objectForKey:@"rtcserverip"];
                                callController.rtcport = [[_msgJson objectForKey:@"rtcserverport"] intValue];
                            }
                      }
                  }
          
                   callController.modalPresentationStyle =  UIModalPresentationFullScreen;
                  [self presentViewController:callController animated:YES completion:^{
                  }];
                  
                  
                  
              }
              
              
          
            
        }
            break;

        case 1112:
        {
            FBDevicesList *devices =  [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@ ",bg_sqlKey(@"bid"),bg_sqlValue(self.bid),bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken])]] firstObject];
            NSString *userid = [[NSUserDefaults standardUserDefaults] objectForKey:@"usr_bid"];
            [YKBusinessFramework open_lockDeviceBid:devices.bid Userbid:userid];
        }
            break;
            
        default:
            break;
    }
}


-(void)updatepicture:(NSNotification *)notification{
   
    NSLog(@"updatepicture begin.");
    NSDictionary* strFileJson = [notification object];
    NSLog(@"strFileJson == %@",strFileJson);
  
    /*
     {
         context = "cid=100";
         "face_name" = "^\U54e5\U54e5^1";
         "face_score" = 100;
         "face_uid" = 394bc178c54f41429f4796eb87e1168c;
         fid = QeRlVeSbKMIG9Sy7;
         filetime = 1586499596454;
         from = 1c7318f60245883b20ce1bf0b97fedc7;
         "has_preview" = 0;
         method = filetrans;
         "op_type" = 0;
     }
     */
    NSString *fid = [strFileJson objectForKey:@"fid"];
 
  
    [self updateReminderShow:fid];
    
    NSLog(@"updatepicture end.");
}

- (void)updateReminderShow:(NSString*)fid{
    
    NSLog(@"updateReminderShow begin.");
  
    NSString *strUrl;
    NSURL *_url = [YKBusinessFramework equesGetRingPictureUrl:self.bid fid:fid context:@""];
    
    NSLog(@"updateReminderShow strUrl = %@", _url);
 
    FBDevicesList *devices =  [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@ ",bg_sqlKey(@"bid"),bg_sqlValue(self.bid),bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken])]] firstObject];
    int camera_id = devices.camera_id;
   
        [AFNHTTPSRequest httpsRequestWithUrlDownloadImage:_url errorHint:^(id errorData) {
        NSLog(@"来电界面图片下载失败");
    } result:^(id value) {
        if (value) {
            UIImage *image = [UIImage imageWithData:value];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (image) {
                   
                    self.incomingImageView.image = image;
                    
                    [self.incomingImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
                        make.left.mas_equalTo(self.view.mas_left);
                        make.right.mas_equalTo(self.view.mas_right);
                        make.height.mas_equalTo((kScreenWidth/16)*9);
                        make.top.mas_equalTo(self.view.mas_top).offset((kScreenHeight*9)/48);
                    }];
                    
                    
                     CGAffineTransform transform = CGAffineTransformIdentity;
                    if (_op_type) {
                        transform = CGAffineTransformRotate(transform, M_PI_2);
                    }else{
                        if (camera_id > 0 && camera_id != 4) {
                            if (camera_id == 3) {
                                transform = CGAffineTransformRotate(transform, M_PI_2);
                            }else if ( camera_id == 5) {
                                
                            }else{
                                transform = CGAffineTransformRotate(transform, -M_PI_2);
                            }
                        }else{
                            
                            if (camera_id == 4) {
                                transform = CGAffineTransformRotate(transform, M_PI);
                            }else{
                                transform = CGAffineTransformRotate(transform, M_PI_2);
                            }
                        }
                    }
                     self.incomingImageView.transform = transform;
                     self.incomingImageView.contentMode = UIViewContentModeScaleAspectFit;
                    
                      
                    
                    
                }
            });
         }
    }];
    
}


-(void)open_smart_lock_result:(NSNotification*)notification
{
    NSDictionary *dict = (NSDictionary*)notification.object;
    switch ([[dict objectForKey:@"ret"] intValue]) {
        case 0:
        {
            [SVProgressHUD dismiss];
            [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Unlocking successful", nil)];
        }
            break;
            
        case 1:
        {
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"开锁失败", nil)];
        
        }
            break;
            
        case 2:
        {
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"门已反锁", nil)];
            
        }
            break;
            
        case 3:
        {
           
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"密码已冻结", nil)];
            
        }
            break;
            
        default:
        {
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"开锁失败", nil)];
        }
            break;
    }
}




@end
